package com.example.finalproject;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyAdapter extends ArrayAdapter {
    private static final String TAG = "yes";
    ArrayList<Database> disheslist;
    ArrayList<Database> disheslistAll;

    public MyAdapter(@NonNull Context context, int resource, ArrayList<Database> List) {
        super(context, resource,List);
        this.disheslist = List;
        this.disheslistAll = new ArrayList<Database>(disheslist);
        Log.i(TAG, "disheslistAll: "+ disheslistAll);
    }
    public View getView(int position, View convertView, ViewGroup parent){
        View itemView = convertView;
        if(itemView == null){
            itemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
        }
        Database list1 = disheslist.get(position);
        TextView name = (TextView) itemView.findViewById(R.id.list_tv1);
        name.setText(list1.getName());
        return itemView;
    }
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            //run as background thread
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                List<Database> filterList = new ArrayList<Database>();
                if(charSequence.toString().isEmpty()){
                    filterList.addAll(disheslistAll);
                }else{
                    for(Database item : disheslistAll){
                        if(item.getName().contains(charSequence)){
                            Log.i(TAG, "item: "+item);
                            filterList.add(item);
                        }
                    }
                }
                FilterResults results = new FilterResults();
                results.values = filterList;
                return results;
            }
            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                disheslist.clear();
                disheslist.addAll((Collection<? extends Database>) filterResults.values);
                notifyDataSetChanged();
            }
        };
        return filter;
    }
}
